<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Controllers\Home\BlogController;

use DB;

use Auth;

use Validate;

use Markdown;

class BlogController extends Controller
{
    /**
     * 首页视图
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        // $blogs = DB::table('blogs')->get();
         $blogs = DB::table('blogs')->paginate(2);

        return view('blog.index', ['blogs'=>$blogs]);
    }

    /**
     * 展现文章添加的视图
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('blog.mk_add');
    }

    /**
     * 保存到数据库   post  /b   ->store
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
         $title = $request->title;
        $content = $request->content;

        //验证
          $this->validate($request,[
            'title'=>'required|max:50',
            'content'=>'required|max:500',
            ]);
          $data = ['title'=> $title,'content'=>$content];
          DB::table('blogs')->insert($data);
          return redirect()->route('b.index');
        
    }


    /**
     * 展示文章详情   /b/id  -> show($id)
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $blog = DB::table('blogs')->where('id', $id)->first();

        $blog->content = Markdown::convertToHtml( $blog->content );

        return view('blog.show',['blog'=>$blog]);
    }

    public function pre_mk(Request $request)
    {
        return  Markdown::convertToHtml($request->cont);
    }

    /**
     * 修改文章
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $blog = DB::table('blogs')->where('id', $id)->first();
        return view('blog.edit',['blog'=>$blog]);
    }

    /**
     * 显示修改后的文章
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        //验证
          $this->validate($request,[
            'title'=>'required|max:50',
            'content'=>'required|max:500',
            ]);

           DB::table('blogs')->where('id',$id)->update(['title'=>$request->title,'content'=>$request->content]);
         return redirect()->route('b.index');
    }

    /**
     * 删除
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        DB::table('blogs')->where('id',$id)->delete();
        return redirect()->route('b.index');

    }
}
